#!/usr/bin/env python3
"""修复ChromaDB路径配置问题"""

import os
import sys
from pathlib import Path

# 添加src目录到Python路径
src_path = Path(__file__).parent / "src"
sys.path.insert(0, str(src_path))

import importlib.util

# 动态导入模块以避免相对导入问题
def load_module(module_path, module_name):
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

# 加载配置模块
config_module = load_module(src_path / "config.py", "config")
load_config = config_module.load_config

# 加载数据库管理器模块
db_manager_module = load_module(src_path / "database" / "manager.py", "database.manager")
DatabaseManager = db_manager_module.DatabaseManager

async def fix_chromadb_path():
    """修复ChromaDB路径配置问题"""
    print("=== ChromaDB路径配置修复工具 ===")
    
    # 1. 检查当前工作目录
    current_dir = os.getcwd()
    print(f"当前工作目录: {current_dir}")
    
    # 2. 加载配置
    print("\n加载配置...")
    config = load_config("config")
    chromadb_config = config.get('databases', {}).get('chromadb', {})
    persist_dir = chromadb_config.get('persist_directory', './data/chroma_db')
    print(f"配置中的persist_directory: {persist_dir}")
    
    # 3. 计算绝对路径
    if os.path.isabs(persist_dir):
        abs_persist_dir = persist_dir
    else:
        abs_persist_dir = os.path.abspath(persist_dir)
    print(f"计算出的绝对路径: {abs_persist_dir}")
    
    # 4. 检查路径是否存在
    if os.path.exists(abs_persist_dir):
        print(f"✓ 路径存在: {abs_persist_dir}")
        items = os.listdir(abs_persist_dir)
        print(f"  包含 {len(items)} 个项目: {items[:5]}{'...' if len(items) > 5 else ''}")
    else:
        print(f"✗ 路径不存在: {abs_persist_dir}")
    
    # 5. 检查可能的其他路径
    possible_paths = [
        "./data/chroma_db",
        "../data/chroma_db", 
        "./src/chroma_db",
        "data/chroma_db",
        "src/chroma_db"
    ]
    
    print("\n检查可能的ChromaDB路径:")
    for path in possible_paths:
        abs_path = os.path.abspath(path)
        if os.path.exists(abs_path):
            items = os.listdir(abs_path)
            print(f"✓ {path} -> {abs_path} (包含 {len(items)} 个项目)")
        else:
            print(f"✗ {path} -> {abs_path} (不存在)")
    
    # 6. 尝试初始化数据库管理器
    print("\n尝试初始化数据库管理器...")
    try:
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        
        # 检查ChromaDB客户端
        if hasattr(db_manager, 'chromadb_client') and db_manager.chromadb_client:
            print("✓ ChromaDB客户端初始化成功")
            
            # 尝试获取实际使用的路径
            client = db_manager.chromadb_client.client
            if hasattr(client, '_settings') and hasattr(client._settings, 'persist_directory'):
                actual_path = client._settings.persist_directory
                print(f"  实际使用的路径: {actual_path}")
            elif hasattr(client, '_path'):
                actual_path = client._path
                print(f"  实际使用的路径: {actual_path}")
            else:
                print("  无法获取实际路径信息")
            
            # 检查conversations集合
            try:
                collection = db_manager.chromadb_client.get_collection('conversations')
                if collection:
                    count = collection.count()
                    print(f"  conversations集合文档数量: {count}")
                else:
                    print("  conversations集合不存在")
            except Exception as e:
                print(f"  检查conversations集合失败: {e}")
        else:
            print("✗ ChromaDB客户端初始化失败")
        
        await db_manager.close()
        
    except Exception as e:
        print(f"✗ 数据库管理器初始化失败: {e}")
    
    # 7. 建议修复方案
    print("\n=== 修复建议 ===")
    print("1. 确保MCP服务器的工作目录设置为: d:\\MCP\\mcp2")
    print("2. 确保ChromaDB数据存储在: d:\\MCP\\mcp2\\data\\chroma_db")
    print("3. 如果数据在其他位置，考虑移动或更新配置")
    
    # 8. 检查MCP配置建议
    print("\n当前MCP配置应该是:")
    print('{')
    print('  "mcpServers": {')
    print('    "mcp2-stdio": {')
    print('      "command": "python",')
    print('      "args": [')
    print('        "-u",')
    print('        "-m",')
    print('        "mcp.main",')
    print('        "--stdio",')
    print('        "--config",')
    print('        "d:\\\\MCP\\\\mcp2\\\\config"')
    print('      ],')
    print('      "env": {')
    print('        "PYTHONPATH": "d:\\\\MCP\\\\mcp2\\\\src",')
    print('        "PYTHONUNBUFFERED": "1",')
    print('        "PYTHONIOENCODING": "utf-8"')
    print('      }')
    print('    }')
    print('  }')
    print('}')

if __name__ == "__main__":
    import asyncio
    asyncio.run(fix_chromadb_path())